package com.xiangxiao.rpan.storage.core;

import com.xiangxiao.rpan.storage.cache.Cache;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/8/18 17:19
 */
@Component(value = "cacheSelector")
public class CacheSelector implements ApplicationContextAware {
  private ApplicationContext applicationContext;

  private Cache cache;

  /**
   * cache类型设置为可配置
   * */
  @Value("${rpan.storage.cache.type}")
  private Class<? extends Cache> cacheType;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
    if (Objects.isNull(cacheType)) {
      throw new RuntimeException("the cache type can not be null!<rpan.cache.type>");
    }
    this.cache = this.applicationContext.getBean(cacheType);
  }

  /**
   * 选择Cache实现类
   *
   * @return
   */
  public Cache select() {
    return cache;
  }
}
